/*年轻人，只管向前看，不要管自暴自弃者的话*/
package com.composetest.core.network

import com.composetest.core.config.Config
import com.composetest.core.network.di.NetworkModule
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit


/**
 * create by itz on 2024-10-15 14:16
 * desc :
 **/
class APIClient {

    private object Holder {
        val INSTANCE = APIClient()
    }

    companion object {
        val instance = Holder.INSTANCE
    }

    // xxxAPI实例化
    fun <T> instanceRetrofit(apiInterface: Class<T>): T {

        // OKHttpClient请求服务器
        val mOkHttpClient = OkHttpClient().newBuilder().myApply {
            // 添加读取超时时间
            readTimeout(10000, TimeUnit.SECONDS)

            // 添加连接超时时间
            connectTimeout(10000, TimeUnit.SECONDS)

            // 添加写出超时时间
            writeTimeout(10000, TimeUnit.SECONDS)

            addInterceptor(
                HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                }
            )
        }.build()

        val retrofit = Retrofit
            .Builder()
            .baseUrl(Config.BASE_URL)
            // 请求方  ←
            .client(mOkHttpClient)
            .addConverterFactory(
                NetworkModule.providesNetworkJson()
                    .asConverterFactory("application/json".toMediaType())
            ) // Json 来解析
            .build()

        return retrofit.create(apiInterface)
    }
}

// 默认 无参数的
fun <T> T.myApply(mm: T.() -> Unit): T {
    // T == this
    mm()
    return this
}